package com.whilelife.Wachovia.account;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Handles all data within the "Other Withdrawals and Service Fees" section
 * Date: Nov 3, 2011
 * Time: 4:03:31 PM
 * @author Brent Merle
 */
public class Withdrawal extends Transaction {


  public Withdrawal(double val, String date, String descr) {
    super(val, date, descr);
  }

  public void setDescription(String description) {
    this.description = description;
  }

  public static List<Withdrawal> parseWithdrawals(BufferedReader br, int endYear) throws IOException {
    ArrayList<Withdrawal> withdrawals = new ArrayList<Withdrawal>();
    String line;
    br.readLine(); //move past the header line
    Withdrawal d = null;
    int firstMonth = -1;
    int year = endYear;
    while ((line = br.readLine()) != null && !line.toLowerCase().startsWith("total")) {
      line = line.trim();

      if (line.matches(TRANSACTION_REGEX)) {
        if (d != null) {
          withdrawals.add(d);
        }
        int idx = line.indexOf(' ', 0);
        String date = line.substring(0, idx);
        int month = Integer.parseInt(date.substring(0, date.indexOf('/')));
        if (month < 10) {
          date = '0' + date;
        }
        if (firstMonth == -1) {
          firstMonth = month;
          if (month == 12) {
            year--;
          }
        } else if (month < firstMonth) {
          firstMonth = month;
          year++;
        }
        date += '/' + String.valueOf(year);

        double val = -1. * Double.parseDouble(line.substring(idx, idx = line.indexOf(' ', idx + 1)).replaceAll(",", ""));
        String desc = line.substring(idx);
        d = new Withdrawal(val, date, desc);
      } else if (line.equalsIgnoreCase("Other Withdrawals and Service Fees continued on next page.")) {
        while (!(br.readLine().equalsIgnoreCase("Date Amount Description"))) {
          //Skips the header (on continuation pages)
        }
      } else if (d != null) {
        d.setDescription(d.getDescription() + ' ' + line);
      }
    }

    if (d != null && !withdrawals.contains(d)) {
      withdrawals.add(d);
    }
    return withdrawals;
  }

  public static double sumWithdrawals(List<Withdrawal> withdrawals) {
    double sum = 0.0;
    for (Withdrawal wd : withdrawals) {
      sum += wd.getValue();
    }
    System.out.println("average is: " + sum / withdrawals.size());
    return sum;
  }

}
